package com.budwk.app.wxprogram.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.budwk.app.base.utils.CoordinateUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.wxprogram.models.Wx_disasterissue;
import com.budwk.app.wxprogram.services.WxDisasterissueService;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

@IocBean
@At("/platform/wxprogram/spider/emergency/information/disaster")
@ApiDefinition(tag = "用户灾情发布")
@Slf4j
public class WxDisasterissueController{
    @Inject
    private WxDisasterissueService wxSpiderEmergencyInformationService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询用户灾情发布")
    @ApiFormParams(
        value = {
            @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
            @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
            @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
            @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
        },
        implementation = Wx_disasterissue.class
    )
    @ApiResponses(
    implementation = Wx_disasterissue.class
    )
   // @SaCheckPermission("wxprogram.spider.emergency.information.disaster")
    public Result<?> list(@Param("..")Wx_disasterissue bean,@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean.getInformationtitle() !=null && Strings.isNotBlank(bean.getInformationtitle().toString())) {
            cnd.and("informationtitle","like","%"+bean.getInformationtitle()+"%");
        }

        if (bean.getInformationcontent() !=null && Strings.isNotBlank(bean.getInformationcontent().toString())) {
            cnd.and("informationcontent","like","%"+bean.getInformationcontent()+"%");
        }

        if (bean.getProvince() !=null && Strings.isNotBlank(bean.getProvince().toString())) {
            cnd.and("province","like","%"+bean.getProvince()+"%");
        }

        if (bean.getCity() !=null && Strings.isNotBlank(bean.getCity().toString())) {
            cnd.and("city","like","%"+bean.getCity()+"%");
        }

        if (bean.getDistrict() !=null && Strings.isNotBlank(bean.getDistrict().toString())) {
            cnd.and("district","like","%"+bean.getDistrict()+"%");
        }

        if (bean.getStreet() !=null && Strings.isNotBlank(bean.getStreet().toString())) {
            cnd.and("street","like","%"+bean.getStreet()+"%");
        }

        if (bean.getInformationchannels() !=null && Strings.isNotBlank(bean.getInformationchannels().toString())) {
            cnd.and("informationchannels","like","%"+bean.getInformationchannels()+"%");
        }

        if (bean.getReleasetime() !=null && Strings.isNotBlank(bean.getReleasetime().toString())) {
            Instant instant = bean.getReleasetime().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("releasetime","between",new Object[]{startdateStr,enddateStr});
        }

        if (bean.getAddtime() !=null && Strings.isNotBlank(bean.getAddtime().toString())) {
            cnd.and("addtime","like","%"+bean.getAddtime().substring(0,10)+"%");
        }

        if (bean.getAddperson() !=null && Strings.isNotBlank(bean.getAddperson().toString())) {
            cnd.and("addperson","like","%"+bean.getAddperson()+"%");
        }

        if (bean.getCreatedate() !=null && Strings.isNotBlank(bean.getCreatedate().toString())) {
            cnd.and("createdate","like","%"+bean.getCreatedate()+"%");
        }

        if (bean.getInformationmedia() !=null && Strings.isNotBlank(bean.getInformationmedia().toString())) {
            cnd.and("informationmedia","like","%"+bean.getInformationmedia()+"%");
        }

        if (bean.getAddphone() !=null && Strings.isNotBlank(bean.getAddphone().toString())) {
            cnd.and("addphone","like","%"+bean.getAddphone()+"%");
        }

        if (bean.getLatitude() !=null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude","like","%"+bean.getLatitude()+"%");
        }

        if (bean.getLongitude() !=null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude","like","%"+bean.getLongitude()+"%");
        }

        if (bean.getPicurl() !=null && Strings.isNotBlank(bean.getPicurl().toString())) {
            cnd.and("picurl","like","%"+bean.getPicurl()+"%");
        }
        if (bean.getDisaster_type() !=null && Strings.isNotBlank(bean.getDisaster_type().toString())) {
            cnd.and("disaster_type","like","%"+bean.getDisaster_type()+"%");
        }
        if (bean.getDisaster_address() !=null && Strings.isNotBlank(bean.getDisaster_address().toString())) {
            cnd.and("disaster_address","like","%"+bean.getDisaster_address()+"%");
        }
        if (bean.getDisaster_class() !=null && Strings.isNotBlank(bean.getDisaster_class().toString())) {
            cnd.and("disaster_class","like","%"+bean.getDisaster_class()+"%");
        }

        if (bean.getVideo_url() !=null && Strings.isNotBlank(bean.getVideo_url().toString())) {
            cnd.and("video_url","like","%"+bean.getVideo_url()+"%");
        }
        if (bean.getDisaster_status() !=null && Strings.isNotBlank(bean.getDisaster_status().toString())) {
            cnd.and("disaster_status","like","%"+bean.getDisaster_status()+"%");
        }


        cnd.and("informationmedia","like","%"+"%东方祥云%").orderBy("addtime","asc");
        //cnd.asc("addtime");

        
        return Result.data(wxSpiderEmergencyInformationService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增用户灾情发布")
    @ApiFormParams(
        implementation = Wx_disasterissue.class
    )
    @ApiResponses
    @SLog(tag = "新增用户灾情发布", value = "${args[0].id}")
    @SaCheckPermission("wxprogram.spider.emergency.information.disaster.create")
    public Result<?> create(@Param("..")Wx_disasterissue wxSpiderEmergencyInformation, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        wxSpiderEmergencyInformation.setCreatedBy(SecurityUtil.getUserId());
        wxSpiderEmergencyInformation.setAddtime(sdf.format(new Date()));
        //判断添加人是否为空
        if (wxSpiderEmergencyInformation.getAddperson().isEmpty()||wxSpiderEmergencyInformation.getAddperson()==null){
            wxSpiderEmergencyInformation.setAddperson(SecurityUtil.getUserUsername());
        }
        //判断添加人手机是否为空
        if (wxSpiderEmergencyInformation.getAddphone().isEmpty()||wxSpiderEmergencyInformation.getAddphone()==null){
            wxSpiderEmergencyInformation.setAddphone(Strings.sNull(SecurityUtil.getSession().get("mobile")));
        }
        //如果地址信息不为空，获取经纬度
        if (!wxSpiderEmergencyInformation.getDisaster_address().isEmpty()||wxSpiderEmergencyInformation.getDisaster_address()!=null){
        Map Coordinate=CoordinateUtils.getLatAndLngByAddr(wxSpiderEmergencyInformation.getDisaster_address());
        wxSpiderEmergencyInformation.setLongitude(Coordinate.get("lng").toString());
        wxSpiderEmergencyInformation.setLatitude(Coordinate.get("lat").toString());
        }
        wxSpiderEmergencyInformationService.insert(wxSpiderEmergencyInformation);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改用户灾情发布")
    @ApiFormParams(
        implementation = Wx_disasterissue.class
    )
    @ApiResponses
    @SLog(tag = "修改用户灾情发布", value = "${args[0].id}")
    @SaCheckPermission("wxprogram.spider.emergency.information.disaster.update")
    public Result<?> update(@Param("..")Wx_disasterissue wxSpiderEmergencyInformation, HttpServletRequest req) {
        wxSpiderEmergencyInformation.setUpdatedBy(SecurityUtil.getUserId());
        wxSpiderEmergencyInformationService.updateIgnoreNull(wxSpiderEmergencyInformation);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取用户灾情发布")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SaCheckPermission("wxprogram.spider.emergency.information.disaster")
    public Result<?> getData(@Param("id")String id, HttpServletRequest req) {
        Wx_disasterissue wxSpiderEmergencyInformation = wxSpiderEmergencyInformationService.fetch(id);
        if (wxSpiderEmergencyInformation == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(wxSpiderEmergencyInformation);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除用户灾情发布")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SLog(tag = "删除用户灾情发布", value = "${args[0]}")
    @SaCheckPermission("wxprogram.spider.emergency.information.disaster.delete")
    public Result<?> delete(@Param("id")String id, HttpServletRequest req) {
        Wx_disasterissue wxSpiderEmergencyInformation = wxSpiderEmergencyInformationService.fetch(id);
        if (wxSpiderEmergencyInformation == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        wxSpiderEmergencyInformationService.delete(id);
        req.setAttribute("_slog_msg", wxSpiderEmergencyInformation.getId());
        return Result.success();
    }
}
